package connect

import (
	"database/sql"
	"fmt"

	"github.com/jmoiron/sqlx"
)

func GetImages(uid int) ([]string, PatientFile) {
	predb, err := sql.Open("sqlserver", "sqlserver://sa:Cdrdicom45@192.168.100.14/CDRDicom?database=CDRData&encrypt=disable")
	if err != nil {
		fmt.Println(err)
	}
	defer predb.Close()

	db := sqlx.NewDb(predb, "sqlserver")
	// force a connection and test that it worked
	err = db.Ping()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("connect db ok!")
	}
	patientFile := PatientFile{}
	schemeList := []Scheme{}
	patients, err := db.Queryx(fmt.Sprintf("select * from Patient where PatientID = '%d'", uid))
	if err != nil {
		fmt.Println(err)
	}
	for patients.Next() {

		var patient Patient
		err = patients.StructScan(&patient)
		if err != nil {
			fmt.Println(err)
		} else {
			// fmt.Printf("%+v\n", patient)
			fmt.Printf("PatientID=%s, NameLast=%s, NameFirst=%s, PatientDR=%s\n", patient.PatientId.String, patient.NameLast, patient.NameFirst.String, patient.BirthDate.Time.Format("02.01.2006"))
		}
		if patient.PatientNumber == 0 {
			emptyString := []string{}
			return emptyString, patientFile
		}
		fmt.Println("Studys")
		studys, err := db.Queryx(fmt.Sprintf("select * from Study where PatientNumber = %d", patient.PatientNumber))
		if err != nil {
			fmt.Println(err)
		}

		for studys.Next() {
			imageList := []ImageFile{}
			study := Study{}
			teeth := map[string][]ImageFile{
				"1":  {},
				"2":  {},
				"3":  {},
				"4":  {},
				"5":  {},
				"6":  {},
				"7":  {},
				"8":  {},
				"9":  {},
				"10": {},
				"11": {},
				"12": {},
				"13": {},
				"14": {},
				"15": {},
				"16": {},
				"17": {},
				"18": {},
				"19": {},
				"20": {},
				"21": {},
			}
			// schemeOne := Scheme{}
			err = studys.StructScan(&study)
			if err != nil {
				fmt.Println(err)
			}

			if study.Description.Valid {
				fmt.Println(study.Description.String, study.StudyDate.Time.Format("02.01.2006"))
			}

			seriess, err := db.Queryx(fmt.Sprintf("select * from Series where StudyNumber = %d", study.StudyNumber))
			if err != nil {
				fmt.Println(err)
			}
			for seriess.Next() {
				series := Series{}
				err = seriess.StructScan(&series)
				if err != nil {
					fmt.Println(err)
				}
				// fmt.Printf("%+v\n", series)
				images, err := db.Queryx(fmt.Sprintf("select * from Image where SeriesNumber = %d", series.SeriesNumber))
				if err != nil {
					fmt.Println(err)
				}

				for images.Next() {
					image := Image{}
					err = images.StructScan(&image)

					if err != nil {
						fmt.Println(err)
					}
					if image.ImageNumberDICOM.Valid && image.ImageFileName.Valid {
						// fmt.Printf("SeriesNumber=%d, SeriesDate=%s\n", series.SeriesNumber, series.SeriesDate.Time.Format("02.01.2006"))
						fmt.Printf("file=%s, number=%s, SeriesDate=%s\n", image.ImageFileName.String, image.ImageNumberDICOM.String, series.SeriesDate.Time.Format("02.01.2006"))
						teeth[image.ImageNumberDICOM.String] = append(teeth[image.ImageNumberDICOM.String], ImageFile{
							image.ImageFileName.String,
							image.ImageNumberDICOM.String,
							image.ImageNumber,
							series.SeriesDate.Time.Format("02.01.2006"),
						})
						imageFile := ImageFile{
							"Rent\\" + image.ImageFileName.String,
							image.ImageNumberDICOM.String, //need to int convert
							image.ImageNumber,
							series.SeriesDate.Time.Format("02.01.2006"),
						}
						imageList = append(imageList, imageFile)
					}
				}

			}
			// schemeOne.SchemeName = study.Description.String
			// schemeOne.SchemeDate = study.StudyDate.Time.Format("02.01.2006")
			// schemeOne.ImageList = imageList
			schemeList = append(schemeList, Scheme{
				SchemeID:   study.StudyID.String,
				SchemeName: study.Description.String,
				SchemeDate: study.StudyDate.Time.Format("02.01.2006"),
				Teeth:      teeth,
				Label:      study.StudyDate.Time.Format("02.01.2006"),
			})

		}
		patientFile = PatientFile{
			patient.PatientId.String,
			patient.NameLast,
			patient.NameFirst.String,
			patient.BirthDate.Time.Format("02.01.20026"),
			schemeList,
		}
	}

	selectSql := fmt.Sprintf(`
	SELECT CDRData.dbo.Image.ImageFileName
  	FROM CDRData.dbo.Patient
  		join CDRData.dbo.Study
  			on CDRData.dbo.Patient.PatientNumber = CDRData.dbo.Study.PatientNumber
  		join CDRData.dbo.Series
  			on CDRData.dbo.Study.StudyNumber = CDRData.dbo.Series.StudyNumber
  		join CDRData.dbo.Image
  			on CDRData.dbo.Series.SeriesNumber = CDRData.dbo.Image.SeriesNumber
  	where CDRData.dbo.Patient.PatientNumber = %d
	`, uid)
	imagesPatient, err := db.Queryx(selectSql)
	if err != nil {
		fmt.Println(err)
	}

	// var basePath = "Rent\\"

	var imageList = []string{}
	for imagesPatient.Next() {
		var img string
		err = imagesPatient.Scan(&img)
		if err != nil {
			fmt.Println(err)
		} else {
			// imageList = append(imageList, basePath+img)
			imageList = append(imageList, img)
		}
	}
	return imageList, patientFile

}

func FileAddressByNumber(imageNumber int) string {
	predb, err := sql.Open("sqlserver", "sqlserver://sa:Cdrdicom45@192.168.100.14/CDRDicom?database=CDRData&encrypt=disable")
	if err != nil {
		fmt.Println(err)
	}
	defer predb.Close()

	db := sqlx.NewDb(predb, "sqlserver")
	// force a connection and test that it worked
	err = db.Ping()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("connect db ok!")
	}

	dicom := db.QueryRow(fmt.Sprintf("select ImageFileName from Image where ImageNumber = '%d'", imageNumber))
	var ImageFileName string
	err = dicom.Scan(&ImageFileName)
	if err != nil {
		fmt.Println(err)
	}
	return ImageFileName
}
